#include "myflash.h"
#include "usart.h"
void flash_init(void)
{
    HAL_FLASH_Unlock();
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP|FLASH_FLAG_OPERR|FLASH_FLAG_WRPERR|
                            FLASH_FLAG_PGAERR|FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR);
    HAL_FLASH_Lock();
}

static uint32_t sector_location(const uint32_t address)
{
    uint32_t sector_num=0;
    if ((address&0x08000000)!=0x08000000)
    {
        sector_num=0;
        return sector_num;
    }
    if (address>=sector1_address&&address<sector2_address)sector_num=FLASH_SECTOR_1;
    if (address>=sector2_address&&address<sector3_address)sector_num=FLASH_SECTOR_2;
    if (address>=sector3_address&&address<sector4_address)sector_num=FLASH_SECTOR_3;
    if (address>=sector4_address&&address<sector5_address)sector_num=FLASH_SECTOR_4;
    if (address>=sector5_address&&address<sector6_address)sector_num=FLASH_SECTOR_5;
    if (address>=sector6_address&&address<sector7_address)sector_num=FLASH_SECTOR_6;
    if (address>=sector7_address&&address<sector8_address)sector_num=FLASH_SECTOR_7;
    if (address>=sector8_address&&address<sector9_address)sector_num=FLASH_SECTOR_8;
    if (address>=sector9_address&&address<sector10_address)sector_num=FLASH_SECTOR_9;
    if (address>=sector10_address&&address<sector11_address)sector_num=FLASH_SECTOR_10;
    if (address>=sector11_address)sector_num=FLASH_SECTOR_11;
    return sector_num;
}

HAL_StatusTypeDef flash_erase(uint32_t address,uint32_t size)
{
    HAL_StatusTypeDef res;
    uint32_t start=0,end=0,i=0;
    HAL_FLASH_Unlock();
    start=sector_location(address);
    end=sector_location(address+size);
    if (!end)
    {
        res=HAL_ERROR;
        return res;
    }
    for (i = start; i < end+1; i++)
    {
        FLASH_Erase_Sector(i,FLASH_VOLTAGE_RANGE_3);
        res=FLASH_WaitForLastOperation(0xffff);
        if (res!=HAL_OK)
        {
            return res;
        }
    }
    HAL_FLASH_Lock();
    return res;
}

HAL_StatusTypeDef flash_program(uint32_t address, uint32_t const * data,const uint32_t len)
{
    HAL_StatusTypeDef res;
    uint16_t i=0;
    uint32_t addressNew=address;
    HAL_FLASH_Unlock();
    for (i = 0; i < len; i++)
    {
        res=HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,addressNew,data[i]);
        if (res!=HAL_OK)
        {
            return res;
        }
        addressNew+=4;
    }
    HAL_FLASH_Lock();
    return res;
}

iapfun jump2app; 

void iap_load_app(uint32_t appxaddr)
{
	if(((*(uint32_t*)appxaddr)&0x2FFE0000)==0x20000000)	//���ջ����ַ�Ƿ�Ϸ�.
	{ 
		jump2app=(iapfun)*(uint32_t*)(appxaddr+4);		//�û��������ڶ�����Ϊ����ʼ��ַ(��λ��ַ)		
		__set_MSP(*(uint32_t*)appxaddr);					//��ʼ��APP��ջָ��(�û��������ĵ�һ�������ڴ��ջ����ַ)
		jump2app();									//��ת��APP.
	}
}	


